package com.xiaoming.backend.config;

import com.xiaoming.backend.dao.mapper.UserPOMapper;
import com.xiaoming.backend.entity.db.example.UserPOExample;
import com.xiaoming.backend.entity.db.po.UserPO;
import com.xiaoming.backend.entity.orm.User;
import com.xiaoming.backend.util.EntityUtil;
import com.xiaoming.backend.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtUtil jwtUtil;
    private final UserDetailsService userDetailsService;
    private final UserPOMapper userPOMapper; // 替换 UserRepository


    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {
        final String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        String jwt = authHeader.substring(7);
        String username = jwtUtil.parseToken(jwt).getSubject();

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 使用 MyBatis-Plus 查询用户
//            QueryWrapper<User> username1 = new QueryWrapper<User>().eq("username", username);
            User user = userPOMapper.selectByUsername(username);

            if (user == null) {
                throw new RuntimeException("用户不存在");
            }
            user.initRole();
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
            if (jwtUtil.validateToken(jwt, username)) {
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        user, // 注入完整 User 对象
                        null,
                        userDetails.getAuthorities()
                );
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
